package com.pan.download1;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.util.List;

public class Page implements Runnable{
    private EdgeDriver edgeDriver;

    private List<String> urlList;

    private int start;

    private int step;

    private Write write;


    public Page(List<String> urlList,int start,int step,Write write) {
        this.urlList = urlList;
        this.start = start;
        this.step = step;
        this.write = write;
    }

    @Override
    public void run() {
        edgeDriver = new EdgeDriver();
        for (int i = start;i<urlList.size();i+=step){
            String url = urlList.get(i);
            String appendStr =getContent(url);
            boolean isWrite = true;
            do {
                isWrite = write.appendContent(i, appendStr);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }while (!isWrite);
            System.out.println("第"+i+"章节下载完成");
        }
        edgeDriver.quit();
    }


    public String getContent(String url){
        edgeDriver.navigate().to(url);
        WebElement contentElement = edgeDriver.findElement(By.id("booktxt"));
        contentElement.findElement(By.cssSelector("b"));//确保该页面加载到了最底部
        String content = contentElement.getText();
        WebElement aElement =  edgeDriver.findElement(By.id("next_url"));
        if (aElement.getText().equals("下一页")){
            String title = edgeDriver.findElement(By.className("bookname")).getText();
            String nextUrl = aElement.getAttribute("href");
            content = "\n\n\n\n\n\n"+title+"\n\n\n" + content + getContent(nextUrl);
        }
        return content;
    }
}
